import React, { useState } from 'react';
import Box from '@mui/material/Box';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import ListItemButton from '@mui/material/ListItemButton';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import RadioGroup from '@mui/material/RadioGroup';
import Radio from '@mui/material/Radio';
import AddIcon from '@mui/icons-material/Add';
// 引入树形结构所需组件
import { SimpleTreeView } from '@mui/x-tree-view/SimpleTreeView';
import { TreeItem } from '@mui/x-tree-view/TreeItem';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import FolderIcon from '@mui/icons-material/Folder';
import ComputerIcon from '@mui/icons-material/Computer';
import IconButton from '@mui/material/IconButton';
import CreateNewFolderIcon from '@mui/icons-material/CreateNewFolder';
import PostAddIcon from '@mui/icons-material/PostAdd';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
// 引入自定义组件
import PasswordField from './PasswordField';

function ConnectionPanel({ 
  connections, 
  addConnection, 
  deleteConnection, 
  updateConnection, 
  renameGroup, 
  connectToServer, 
  disconnectFromServer, 
  activeConnection 
}) {
  // 状态管理
  const [open, setOpen] = useState(false);
  const [connectionForm, setConnectionForm] = useState({
    host: '',
    port: '22',
    username: '',
    authType: 'password',
    password: '',
    privateKey: '',
    group: '' // 添加分组字段
  });
  
  // 分组对话框状态
  const [groupDialogOpen, setGroupDialogOpen] = useState(false);
  const [groupName, setGroupName] = useState('');
  const [parentGroup, setParentGroup] = useState('');
  
  // 右键菜单状态
  const [contextMenu, setContextMenu] = useState(null);
  const [selectedItem, setSelectedItem] = useState(null);
  
  // 编辑模式状态
  const [isEditMode, setIsEditMode] = useState(false);
  
  // 删除确认对话框状态
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState(null); // 新增：保存要删除的项目
  
  // 重命名分组对话框状态
  const [renameGroupDialogOpen, setRenameGroupDialogOpen] = useState(false);
  const [newGroupName, setNewGroupName] = useState('');
  const [newGroupId, setNewGroupId] = useState('');
  
  // 打开对话框
  const handleClickOpen = () => {
    setOpen(true);
  };
  
  // 关闭对话框
  const handleClose = () => {
    setOpen(false);
    // 如果是编辑模式，退出编辑模式
    if (isEditMode) {
      setIsEditMode(false);
      // 重置表单
      setConnectionForm({
        host: '',
        port: '22',
        username: '',
        authType: 'password',
        password: '',
        privateKey: '',
        group: ''
      });
    }
  };
  
  // 表单变更处理
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setConnectionForm({
      ...connectionForm,
      [name]: value
    });
  };
  
  // 添加连接
  const handleAddConnection = () => {
    // 验证表单
    if (!connectionForm.host || !connectionForm.username) {
      return;
    }
    
    // 添加连接并保存
    addConnection(connectionForm, true);
    
    // 重置表单并关闭对话框
    setConnectionForm({
      host: '',
      port: '22',
      username: '',
      authType: 'password',
      password: '',
      privateKey: '',
      group: ''
    });
    setOpen(false);
  };
  
  // 连接/断开处理
  const handleConnectionAction = (connectionId, status) => {
    if (status === 'connected' || status === 'connecting') {
      disconnectFromServer(connectionId);
    } else {
      connectToServer(connectionId);
    }
  };
  
  // 获取状态样式
  const getStatusClass = (status) => {
    switch (status) {
      case 'connected':
        return 'status-connected';
      case 'connecting':
        return 'status-connecting';
      default:
        return 'status-disconnected';
    }
  };
  
  // 获取状态文本
  const getStatusText = (status) => {
    switch (status) {
      case 'connected':
        return '已连接';
      case 'connecting':
        return '连接中...';
      case 'error':
        return '连接错误';
      default:
        return '未连接';
    }
  };
  
  // 打开新建分组对话框
  const handleOpenGroupDialog = () => {
    setGroupDialogOpen(true);
  };
  
  // 关闭新建分组对话框
  const handleCloseGroupDialog = () => {
    setGroupDialogOpen(false);
    setGroupName('');
    setParentGroup('');
  };
  
  // 添加新分组
  const handleAddGroup = () => {
    if (!groupName) return;
    
    // 创建新分组对象，确保ID唯一
    const newGroup = {
      id: `group-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
      name: groupName,
      type: 'group',
      parentId: parentGroup || null
    };
    
    // 添加到连接列表中
    addConnection(newGroup, true);
    
    // 关闭对话框
    handleCloseGroupDialog();
  };
  
  // 构建树形结构数据
  const buildTreeData = (items, parentId = null) => {
    return items
      .filter(item => {
        // 确保我们正确过滤项目，避免 parentId 为 undefined 的情况
        if (parentId === null) {
          return item.parentId === null || item.parentId === undefined;
        }
        return item.parentId === parentId;
      })
      .map(item => {
        // 确保每个项目都有一个有效的唯一ID
        const uniqueId = item.id || `generated-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
        
        return {
          ...item,
          id: uniqueId,
          children: buildTreeData(items, uniqueId)
        };
      });
  };
  
  // 将连接数据转换为树形结构
  const getTreeData = () => {
    // 添加类型标识，区分连接和分组
    const itemsWithType = connections.map(conn => ({
      ...conn,
      type: conn.type || 'connection'
    }));
    
    return buildTreeData(itemsWithType);
  };
  
  // 打开右键菜单
  const handleContextMenu = (event, item) => {
    event.preventDefault();
    event.stopPropagation();
    setContextMenu({ mouseX: event.clientX, mouseY: event.clientY });
    setSelectedItem(item);
  };
  
  // 关闭右键菜单
  const handleCloseContextMenu = () => {
    setContextMenu(null);
    setSelectedItem(null);
  };

  // 打开删除确认对话框
  const handleOpenDeleteDialog = () => {
    setItemToDelete(selectedItem); // 保存当前选中项
    setDeleteDialogOpen(true);
    handleCloseContextMenu();
  };
  
  // 关闭删除确认对话框
  const handleCloseDeleteDialog = () => {
    setDeleteDialogOpen(false);
    // 不要在这里清除 itemToDelete，以便删除操作可以使用它
  };
  
  // 删除连接或分组
  const handleDelete = () => {
    if (itemToDelete) {
      // 调用App.jsx中的删除函数
      deleteConnection(itemToDelete.id, true);
      
      // 关闭对话框
      setDeleteDialogOpen(false);
      setItemToDelete(null); // 清除要删除的项目
    } else {
      console.error('没有选择要删除的项目');
    }
  };
  
  // 打开重命名分组对话框
  const handleOpenRenameGroupDialog = (group) => {
    setNewGroupName(group.name);
    setNewGroupId(group.id);
    setRenameGroupDialogOpen(true);
    handleCloseContextMenu();
  };
  
  // 关闭重命名分组对话框
  const handleCloseRenameGroupDialog = () => {
    setRenameGroupDialogOpen(false);
    setNewGroupName('');
    setNewGroupId('');
  };
  
  // 重命名分组
  const handleRenameGroup = () => {
    console.log('selectedItem:', selectedItem);
    if (newGroupId && newGroupName) {
      // 调用App.jsx中的重命名分组函数
      renameGroup(newGroupId, newGroupName, true);
      
      // 关闭对话框
      setRenameGroupDialogOpen(false);
      setNewGroupName('');
      setNewGroupId('');
    }
  };

  // 修改编辑连接的处理函数，使用updateConnection
  const handleEditConnection = (connection) => {
    setConnectionForm({
      id: connection.id,
      host: connection.host || '',
      port: connection.port || '22',
      username: connection.username || '',
      authType: connection.authType || 'password',
      password: connection.password || '',
      privateKey: connection.privateKey || '',
      group: connection.parentId || '',
      type: connection.type || 'connection'
    });
    setIsEditMode(true);
    setOpen(true);
    handleCloseContextMenu();
  };

  // 在选定分组下创建新连接
  const handleCreateConnectionInGroup = (groupId) => {
    setConnectionForm({
      ...connectionForm,
      group: groupId
    });
    setOpen(true);
    handleCloseContextMenu();
  };
  
  // 在选定分组下创建子分组
  const handleCreateSubGroup = (parentGroupId) => {
    setParentGroup(parentGroupId);
    setGroupDialogOpen(true);
    handleCloseContextMenu();
  };
  
  // 递归渲染树节点
  const renderTree = (nodes) => {
    return nodes.map((node) => {
      // 确保每个节点都有唯一ID
      const nodeId = String(node.id || `node-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`);
      console.log('nodeId:', nodeId);
      
      return (
        <TreeItem
          itemId={nodeId}
          key={nodeId}
          nodeId={nodeId}
          label={
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              py: 0.5
            }}
            onContextMenu={(e) => handleContextMenu(e, node)}
          >
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              {node.type === 'group' ? (
                <FolderIcon color="primary" sx={{ mr: 1 }} />
              ) : (
                <>
                  <ComputerIcon sx={{ mr: 1 }} />
                  <span className={`status-indicator ${getStatusClass(node.status)}`}></span>
                </>
              )}
              <Typography variant="body2">
                {node.type === 'group' 
                  ? node.name 
                  : `${node.username}@${node.host}:${node.port} - ${getStatusText(node.status)}`}
              </Typography>
            </Box>
            {node.type === 'connection' && (
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleContextMenu(e, node);
                }}
              >
                <MoreVertIcon fontSize="small" />
              </IconButton>
            )}
          </Box>
        }
        onClick={() => {
          if (node.type === 'connection') {
            handleConnectionAction(node.id, node.status);
          }
        }}
        sx={{
          '&.Mui-selected': {
            backgroundColor: 'action.selected',
          }
        }}
      >
        {Array.isArray(node.children) && node.children.length > 0
          ? renderTree(node.children)
          : null}
      </TreeItem>
      )
    });
  };
  
  // 获取所有分组选项，用于下拉菜单
  const getGroupOptions = () => {
    return connections
      .filter(item => item.type === 'group')
      .map(group => (
        <MenuItem key={group.id} value={group.id}>{group.name}</MenuItem>
      ));
  };
  
  const treeData = getTreeData();
  
  return (
    <Box className="connection-panel" sx={{ width: 300, borderRight: 1, borderColor: 'divider' }}>
      <Box sx={{ p: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6">连接</Typography>
        <Box>
          <IconButton size="small" onClick={handleClickOpen}>
            <PostAddIcon fontSize="small" />
          </IconButton>
          <IconButton size="small" onClick={handleOpenGroupDialog}>
            <CreateNewFolderIcon fontSize="small" />
          </IconButton>
        </Box>
      </Box>
      
      <Divider />
      
      {connections.length === 0 ? (
        <List>
          <ListItem>
            <ListItemText primary="没有保存的连接" secondary="点击新建按钮添加连接" />
          </ListItem>
        </List>
      ) : (
        <SimpleTreeView
          defaultCollapseIcon={<ExpandMoreIcon />}
          defaultExpandIcon={<ChevronRightIcon />}
          sx={{ height: 'calc(100vh - 120px)', overflowY: 'auto', p: 1 }}
        >
          {renderTree(treeData)}
        </SimpleTreeView>
      )}
      
      {/* 新建/编辑连接对话框 */}
      <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>
          <Typography variant="subtitle1">
            {isEditMode ? '编辑SSH连接' : '新建SSH连接'}
          </Typography>
        </DialogTitle>
        <DialogContent>
          <TextField
            margin="dense"
            label="主机地址"
            type="text"
            fullWidth
            variant="outlined"
            name="host"
            value={connectionForm.host}
            onChange={handleFormChange}
            size="small"
            sx={{ my: 1 }}
          />
          <TextField
            margin="dense"
            label="用户名"
            type="text"
            fullWidth
            variant="outlined"
            name="username"
            value={connectionForm.username}
            onChange={handleFormChange}
            size="small"
            sx={{ my: 1 }}
          />
          <FormControl component="fieldset" sx={{ mt: 2 }}>
            <Typography variant="subtitle2">认证方式</Typography>
            <RadioGroup
              name="authType"
              value={connectionForm.authType}
              onChange={handleFormChange}
              row
            >
              <FormControlLabel value="password" control={<Radio size="small" />} label="密码" />
              <FormControlLabel value="privateKey" control={<Radio size="small" />} label="私钥" />
            </RadioGroup>
          </FormControl>
          
          {connectionForm.authType === 'password' ? (
            <PasswordField
              value={connectionForm.password}
              onChange={handleFormChange}
              name="password"
            />
          ) : (
            <TextField
              margin="dense"
              label="私钥内容"
              multiline
              rows={4}
              fullWidth
              variant="outlined"
              name="privateKey"
              value={connectionForm.privateKey}
              onChange={handleFormChange}
              size="small"
              sx={{ my: 1 }}
            />
          )}
          <TextField
            margin="dense"
            label="端口"
            type="text"
            fullWidth
            variant="outlined"
            name="port"
            value={connectionForm.port}
            onChange={handleFormChange}
            size="small"
            sx={{ my: 1 }}
          />
          
          {/* 添加分组选择 */}
          <FormControl fullWidth size="small" sx={{ my: 1 }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>分组</Typography>
            <TextField
              select
              name="group"
              value={connectionForm.group}
              onChange={handleFormChange}
              variant="outlined"
              size="small"
            >
              <MenuItem value="">无分组</MenuItem>
              {getGroupOptions()}
            </TextField>
          </FormControl>
        </DialogContent>
        <DialogActions sx={{ display: 'flex', justifyContent: 'space-between', px: 2, pb: 2 }}>
          <Button 
            onClick={handleClose} 
            size="small"
          >
            取消
          </Button>
          <Box>
            {isEditMode ? (
              <Button 
                onClick={() => {
                  // 验证表单
                  if (!connectionForm.host || !connectionForm.username) {
                    return;
                  }
                  
                  // 更新连接并保存
                  updateConnection({
                    ...connectionForm,
                    parentId: connectionForm.group || null
                  }, true);
                  
                  // 重置表单并关闭对话框
                  setConnectionForm({
                    host: '',
                    port: '22',
                    username: '',
                    authType: 'password',
                    password: '',
                    privateKey: '',
                    group: ''
                  });
                  setOpen(false);
                  setIsEditMode(false);
                }} 
                variant="contained" 
                size="small" 
                color="primary"
              >
                保存修改
              </Button>
            ) : (
              <>
                <Button 
                  onClick={() => {
                    // 验证表单
                    if (!connectionForm.host || !connectionForm.username) {
                      return;
                    }
                    
                    // 添加连接并保存
                    const newConnectionId = addConnection({
                      ...connectionForm,
                      parentId: connectionForm.group || null
                    }, true);
                    
                    // 重置表单并关闭对话框
                    setConnectionForm({
                      host: '',
                      port: '22',
                      username: '',
                      authType: 'password',
                      password: '',
                      privateKey: '',
                      group: ''
                    });
                    setOpen(false);
                    
                    // 连接到服务器
                    connectToServer(newConnectionId);
                  }} 
                  variant="contained" 
                  size="small" 
                  color="primary"
                  sx={{ ml: 1 }}
                >
                  保存并连接
                </Button>
                <Button 
                  onClick={() => {
                    // 验证表单
                    if (!connectionForm.host || !connectionForm.username) {
                      return;
                    }
                    
                    // 添加连接并保存
                    addConnection({
                      ...connectionForm,
                      parentId: connectionForm.group || null
                    }, true);
                    
                    // 重置表单并关闭对话框
                    setConnectionForm({
                      host: '',
                      port: '22',
                      username: '',
                      authType: 'password',
                      password: '',
                      privateKey: '',
                      group: ''
                    });
                    setOpen(false);
                  }} 
                  variant="outlined" 
                  size="small"
                  sx={{ ml: 1 }}
                >
                  保存
                </Button>
                <Button 
                  onClick={() => {
                    // 验证表单
                    if (!connectionForm.host || !connectionForm.username) {
                      return;
                    }
                    
                    // 创建临时连接并连接
                    const tempConnection = {
                      ...connectionForm,
                      id: `temp-${Date.now()}`,
                      status: 'disconnected',
                      temp: true
                    };
                    
                    // 添加临时连接但不保存
                    const tempConnectionId = addConnection(tempConnection, false);
                    
                    // 连接到服务器
                    connectToServer(tempConnectionId);
                    
                    // 关闭对话框
                    setOpen(false);
                  }} 
                  variant="text" 
                  size="small"
                  sx={{ ml: 1 }}
                >
                  连接
                </Button>
              </>
            )}
          </Box>
        </DialogActions>
      </Dialog>
      
      {/* 新建分组对话框 */}
      <Dialog open={groupDialogOpen} onClose={handleCloseGroupDialog} maxWidth="xs" fullWidth>
        <DialogTitle>新建分组</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="分组名称"
            type="text"
            fullWidth
            variant="outlined"
            value={groupName}
            onChange={(e) => setGroupName(e.target.value)}
            size="small"
            sx={{ my: 1 }}
          />
          <FormControl fullWidth size="small" sx={{ my: 1 }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>父级分组</Typography>
            <TextField
              select
              value={parentGroup}
              onChange={(e) => setParentGroup(e.target.value)}
              variant="outlined"
              size="small"
            >
              <MenuItem value="">无父级分组</MenuItem>
              {getGroupOptions()}
            </TextField>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseGroupDialog} size="small">取消</Button>
          <Button onClick={handleAddGroup} variant="contained" size="small">创建</Button>
        </DialogActions>
      </Dialog>
      
      {/* 右键菜单 */}
      <Menu
        open={contextMenu !== null}
        onClose={handleCloseContextMenu}
        anchorReference="anchorPosition"
        anchorPosition={
          contextMenu !== null
            ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
            : undefined
        }
      >
        {selectedItem && selectedItem.type === 'connection' && (
          <>
            <MenuItem onClick={() => {
              handleConnectionAction(selectedItem.id, selectedItem.status);
              handleCloseContextMenu();
            }}>
              {selectedItem.status === 'connected' ? '断开连接' : '连接'}
            </MenuItem>
            <MenuItem onClick={() => handleEditConnection(selectedItem)}>编辑</MenuItem>
            <MenuItem onClick={handleOpenDeleteDialog}>删除</MenuItem>
          </>
        )}
        {selectedItem && selectedItem.type === 'group' && (
          <>
            <MenuItem onClick={() => handleCreateConnectionInGroup(selectedItem.id)}>新建连接</MenuItem>
            <MenuItem onClick={() => handleCreateSubGroup(selectedItem.id)}>新建子分组</MenuItem>
            <MenuItem onClick={() => handleOpenRenameGroupDialog(selectedItem)}>重命名</MenuItem>
            <MenuItem onClick={handleOpenDeleteDialog}>删除</MenuItem>
          </>
        )}
      </Menu>
      
      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onClose={handleCloseDeleteDialog} maxWidth="xs">
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            {selectedItem && selectedItem.type === 'group' 
              ? '确定要删除此分组及其所有子项吗？' 
              : '确定要删除此连接吗？'}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDeleteDialog} size="small">取消</Button>
          <Button onClick={handleDelete} color="error" variant="contained" size="small">删除</Button>
        </DialogActions>
      </Dialog>
      
      {/* 重命名分组对话框 */}
      <Dialog open={renameGroupDialogOpen} onClose={handleCloseRenameGroupDialog} maxWidth="xs">
        <DialogTitle>重命名分组</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="分组名称"
            type="text"
            fullWidth
            variant="outlined"
            value={newGroupName}
            onChange={(e) => setNewGroupName(e.target.value)}
            size="small"
            sx={{ my: 1 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseRenameGroupDialog} size="small">取消</Button>
          <Button onClick={handleRenameGroup} variant="contained" size="small">保存</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default ConnectionPanel;